<template>
    <el-dialog v-model="dialog" @close="close" :append-to-body="true" width="730px" title="新建合同">
        <el-form :model="form" :rules="rules" size="small" class="contractForm" label-width="105px" ref="refForm">
            <el-divider content-position="left">合同基础信息</el-divider>
            <el-form-item label="合同主题:" prop="name">
                <el-input v-model="form.name" placeholder="请输入"></el-input>
            </el-form-item>
            <el-row class="row-item">
                <el-col :span="12">
                    <el-form-item label="合同编号:" prop="code">
                        <el-input v-model="form.code" placeholder="选填, 空则系统自动生成"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户名称:" prop="name">{{form.name || '-'}}</el-form-item>
                </el-col>
            </el-row>
            <el-row class="row-item">
                <el-col :span="12">
                    <el-form-item label="合同金额" prop="total">
                        <el-input-number v-model="form.total" :min="0" :step="0.01" />
                        <el-checkbox v-model="form.isTaxs" label="是否含税" size="small" style="margin-left:10px;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结付方式" prop="payType">
                        <el-select v-model="form.payType" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in payTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="row-item">
                <el-col :span="12">
                    <el-form-item label="合同分类" prop="contractType">
                        <el-select v-model="form.contractType" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in contractTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <el-icon style="margin-left:5px;"><ele-Setting /></el-icon>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="机会" prop="opportunity">
                        <el-select v-model="form.opportunity" placeholder="请选择" size="small">
                            <el-option
                                v-for="item in opportunityList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                        <el-icon style="margin-left:5px;"><ele-Setting /></el-icon>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
            <el-divider content-position="left">订单详情</el-divider>
            <el-table size="small" :data="form.order" border>
                <el-table-column label="编号" prop="code"></el-table-column>
                <el-table-column label="产品型号" prop="model"></el-table-column>
                <el-table-column label="产品详情" prop="detail"></el-table-column>
                <el-table-column label="数量" prop="num" width="44px"></el-table-column>
                <el-table-column label="单价" prop="price" width="44px"></el-table-column>
                <el-table-column label="折扣" prop="discount" width="44px"></el-table-column>
                <el-table-column label="合计" prop="total" width="44px"></el-table-column>
                <el-table-column label="税率" prop="taxs" width="44px"></el-table-column>
                <el-table-column label="发货日期" prop="sendDate"></el-table-column>
                <el-table-column label="货运方式" prop="logisticType"></el-table-column>
            </el-table>
            <div class="form-shadow-none">
                <el-form-item label="备注" label-width="45px" style="border:1px solid var(--el-border-color-lighter);border-top: none;">
                    <el-input type="textarea" v-model="form.orderRemark" placeholder="请输入"></el-input>
                </el-form-item>
            </div>
            <el-row justify="space-between" style="margin-top:10px;">
                <el-form-item label="合计金额" prop="form.totalOrder">
                    <el-input-number v-model="form.totalOrder" :min="0" :step="0.01" />
                </el-form-item>
                <el-form-item label="整单折扣" prop="form.orderDiscount" style="align-items:flex-start">
                    <el-input-number v-model="form.orderDiscount" :min="0" :step="0.01" />
                </el-form-item>
            </el-row>
            <el-divider style="margin-top:18px;" content-position="left">自定义信息</el-divider>
            <el-row class="row-item" style="margin-bottom:0px">
                <el-col :span="12">
                    <el-form-item label="合同开始时间" prop="contractStart">
                        <el-date-picker v-model="form.contractStart" type="date" placeholder="请选择" size="small" :disabled-date="disabledStart" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="合同结束时间" prop="contractEnd">
                        <el-date-picker v-model="form.contractEnd" type="date" placeholder="请选择" size="small" :disabled-date="disabledEnd" value-format="YYYY-MM-DD" />
                        <el-checkbox v-model="form.endAlert" label="到期前1个月提醒" size="small" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="row-item">
                <el-col :span="12">
                    <el-form-item label="对方签约人" prop="customerSign">
                        <el-select v-model="form.customerSign" placeholder="请选择" size="small" filterable>
                            <el-option
                                v-for="item in customerList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="我方签约人" prop="customerSign">
                        <span>{{form.signPerson || '-'}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="row-item">
                <el-col :span="12">
                    <el-form-item label="主联系方式" prop="customerContact">
                        {{form.customerContact || '-'}}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="主联系方式" prop="customerSign">
                        <span>{{form.signContact || '-'}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="row-item">
                <el-col :span="24" style="margin-bottom:10px;">
                    <span style="font-size:12px;">合同正文和条款:</span>
                </el-col>
                <el-col :span="24">
                    <Editor :is-disable="false" v-model="form.contractDetail" placeholder="复制粘贴合或输入" />
                </el-col>
            </el-row>
            <el-divider content-position="left">收货人信息</el-divider>
            <el-form-item label="选择收货人">
                <el-radio-group v-model="receipt" @change="changeReceipt">
                    <el-radio label="0" size="small">历史收件人</el-radio>
                    <el-radio label="1" size="small">客户联系人</el-radio>
                    <el-radio label="2" size="small">新建联系人</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-row justify="center" align="middle" v-if="receipt == 2 && form.receiptList.length < 1" @click="addContact">
                <el-icon size="26px" color="var(--el-color-primary)"><ele-CirclePlusFilled /></el-icon>
                <span style="margin-left:5px;font-size:13px;color:var(--el-text-color-regular)">新建联系人</span>
            </el-row>
            <el-table v-if="receipt != 2 || (receipt == 2 && form.receiptList.length > 0)" :data="form.receiptList" size="small" border>
                <el-table-column label="收货人" prop="name">
                    <template #default="scope">
                        <span v-if="receipt != 2">{{scope.row.name}}</span>
                        <el-input v-else v-model="form.receiptList[scope.$index].name" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="联系电话" prop="phone">
                    <template #default="scope">
                        <span v-if="receipt != 2">{{scope.row.phone}}</span>
                        <el-input v-else v-model="form.receiptList[scope.$index].phone" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="收货地址" prop="address" width="400px">
                    <template #default="scope">
                        <span v-if="receipt != 2">{{scope.row.address}}</span>
                        <el-input v-else v-model="form.receiptList[scope.$index].address" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="receipt == 2" label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" link v-if="scope.$index == form.receiptList.length - 1" @click="addContact">添加</el-button>
                        <el-button size="small" type="danger" link v-if="scope.$index > 0" @click="delContact(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            
        </el-form>
        <el-row class="footer-fixed">
            <el-button size="small" type="warning" @click="submitDraft(refForm)">保存为草稿</el-button>
            <el-button size="small" type="primary" @click="submit(refForm)">保存</el-button>
            <el-button size="small" @click="cancel(refForm)">取消</el-button>
        </el-row>
    </el-dialog>
</template>
<script>
import { toRefs, computed, reactive, ref } from 'vue'
import Editor from '/@/components/editor/index.vue';

export default {
    name: 'ContractCreate',
    props: {
        dialogPop: {
            type: Boolean,
            default: false
        }
    },
    components: {
        Editor
    },
    setup(props, context) {

        const { dialogPop } = toRefs(props)
        const dialog = computed({
            get: () => dialogPop.value,
            set: (val) => {
                context.emit('update:dialogPop', val)
            }
        })
        const validateContractStart = (rule, value, callback) => {
            if(value && state.form.contractEnd) {
                const start = new Date(value + ' 00:00:00').getTime()
                const end = new Date(state.form.contractEnd + ' 00:00:00').getTime()
                if(end <= start) {
                    callback(new Error('合同开始时间不能大于结束时间'))
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        const validateContractEnd = (rule, value, callback) => {
            if(value && state.form.contractEnd) {
                const start = new Date(state.form.contractStart + ' 00:00:00').getTime()
                const end = new Date(value + ' 00:00:00').getTime()
                if(end <= start) {
                    callback(new Error('合同结束时间不能小于结束时间'))
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        const state = reactive({
            form: {
                total: 0,
                isTaxs: true,
                contractStart: '',
                order: [{code: '123456789', model: 'A380', detail: '秸秆麦子', num: 10, price: 66, discount: 0.6, total: 999, taxs: '15%', sendDate: '2023-02-23', logisticType: '海运'}],
                contractEnd: '',
                endAlert: false,
                receiptList: []
            },
            rules: {
                total: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
                payType: [{ required: true, message: '结付方式', trigger: 'blur' }],
                contractType: [{ required: true, message: '合同分类', trigger: 'blur' }],
                contractStatus: [{ required: true, message: '合同状态', trigger: 'blur' }],
                contractStart: [{ validator: validateContractStart, trigger: 'blur' }],
                contractEnd: [{ validator: validateContractEnd, trigger: 'blur' }]
            },
            payTypeList: [{
                label: '全款结付',
                value: '0'
            },{
                label: '分期付款',
                value: '1'
            }],
            contractTypeList: [{
                label: '自定义',
                value: '0'
            }],
            opportunityList: [{
                label: '产品A',
                value: '0'
            }],
            customerList: [{
                label: '客户1',
                value: '0'
            }],
            disabledStart: (time) => {
                return time.getTime() > new Date(state.form.contractEnd + ' 00:00:00').getTime()
            },
            disabledEnd: (time) => {
                return time.getTime() < new Date(state.form.contractStart + ' 00:00:00').getTime()
            },
            receipt: '0'
        })
        const refForm = ref()
        const close = () => {
            context.emit("update:dialogPop", false)
        }
        const submitDraft = async (formEl) => {
            console.log(formEl)
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
                    context.emit('onSubmit', true)
                    context.emit("update:dialogPop", false)
                }
            })
        }
        const submit = async (formEl) => {
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
                    context.emit('onSubmit', true)
                    context.emit("update:dialogPop", false)
                }
            })
        }
        const cancel = async (formEl) => {
            if (!formEl) return
            formEl.resetFields()
            context.emit("update:dialogPop", false)
        }
        const addContact = () => {
            state.form.receiptList.push({})
        }
        const delContact = (index) => {
            state.form.receiptList.splice(index, 1)
        }
        const changeReceipt = e => {
            console.log(e)
            state.form.receiptList = []
        }
        return {
            dialog,
            close,
            submit,
            cancel,
            addContact,
            delContact,
            changeReceipt,
            refForm,
            submitDraft,
            ...toRefs(state)
        }
    }
}
</script>
<style lang="scss" scoped>
.contractForm{
    padding-bottom: 80px;
    :deep(.el-divider) {
        margin-top: 0;
    }
    .row-item{
        margin-bottom: 18px;
    }
    .form-shadow-none{
        :deep(.el-textarea__inner) {
            box-shadow: none;
            padding: 3px 0;
        }
    }
}
.footer-fixed{
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    padding: 10px;
    background: #fff;
    z-index: 999;
    display: flex;
    justify-content: center;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
}
</style>